<template>
  <div class="city_container">
    <!-- 固定的搜索框 -->
    <div class="search">
      <input type="text" placeholder="输入要查询的省份或城市" />
      <span><Icon type="icon-sousuo3" Styles="font-size:28px"></Icon></span>
    </div>
    <div class="content">
      <div class="hot_city">
        <div class="tag"></div>
        <div class="msg">
          <div>热门城市</div>
          <div>
            <span
              :class="{ rotated: !hotShow, antiRotated: hotShow }"
              @click="hotShow = !hotShow"
              ><i class="iconfont icon-jiantouxia"></i
            ></span>
            <span>一线和新一线城市</span>
            <span>《2023城市商业魅力排行榜》</span>
            <span
              ><label
                ><input
                  type="checkbox"
                  v-model="HotAllActive"
                  @change="handleCheckboxChange" /></label
            ></span>
          </div>
          <div v-if="hotShow">
            <span
              v-for="(item, index) in newHotCities"
              :key="index"
              :class="{ active: item.flag }"
              @click="handleActive(index)"
            >
              {{ item.name }}
            </span>
          </div>
        </div>
      </div>
      <div class="all_city">
        <div class="tag"></div>
        <div class="msg">
          <div class="title">热门城市</div>
          <div
            class="item"
            v-for="(item, provinceIndex) in NewAllCities"
            :key="item.id"
          >
            <div class="father">
              <span
                v-if="item.children.length > 0"
                @click="item.flag = !item.flag"
                class="jiantou"
                :class="{ rotated: !item.flag, antiRotated: item.flag }"
                ><i class="iconfont icon-jiantouxia"></i
              ></span>
              <span class="jiantou" v-else></span>
              <span class="province">{{ item.province }}</span>
              <span class="check"
                ><label
                  ><input
                    type="checkbox"
                    ref="checkbox"
                    v-model="item.selected"
                    @change="
                      handleProvinceChange(provinceIndex, $event)
                    " /></label
              ></span>
            </div>
            <div
              class="child"
              v-show="item.flag"
              v-for="(child, cityIndex) in item.children"
              :key="child"
            >
              <span class="check">
                <label
                  ><input
                    type="checkbox"
                    ref="checkbox"
                    v-model="child.selected"
                    @change="handleCheckCity(provinceIndex, cityIndex, $event)"
                /></label>
              </span>
              <span class="children">{{ child.name }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="computed">
      <div>
        已选
        <span class="num">{{ checkCities.length }}</span>
        个
        <span
          v-if="checkCities.length > 0"
          class="jiantou"
          :class="{ rotate: watch, antiRotated: !watch }"
          @click="watch = !watch"
          ><i class="iconfont icon-jiantouxia"></i
        ></span>
      </div>
      <div>
        <button @click="clearChecked">清除院校城市</button>
      </div>
      <div>
        <router-link to="/school_i">
          <button @click="confirmSelection">确定</button>
        </router-link>
      </div>
    </div>
    <div class="watch" v-if="watch">
      <div class="example">
        <div class="title">
          <span>已选内容</span>
          <span @click="watch = !watch"
            ><i class="iconfont icon-quxiao"></i
          ></span>
        </div>
        <div class="city">
          <div>
            院校城市<span>（{{ checkCities.length }}）</span>
          </div>
          <div>
            <span v-for="(item, index) in checkCities" :key="index">
              {{ item }}
              <div class="mark" @click="cancelChecked(index)">
                <i class="iconfont icon-quxiao"></i>
              </div>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Icon from "@/components/Icon.vue";

export default {
  name: "cityComponent",
  components: {
    Icon,
  },
  data() {
    return {
      // 热门城市
      hotCities: [
        "上海",
        "北京",
        "广州",
        "深圳",
        "成都",
        "重庆",
        "杭州",
        "武汉",
        "苏州",
        "西安",
        "南京",
        "长沙",
        "天津",
        "郑州",
        "东莞",
        "青岛",
        "昆明",
        "宁波",
        "合肥",
      ],
      newHotCities: [],
      // 所有的城市
      allCities: [
        {
          id: 15436,
          province: "安徽",
          children: ["合肥", "芜湖", "安庆", "宿州", "淮南", "淮北", "宣城"],
        },
        {
          id: 22246,
          province: "重庆",
          children: [],
        },
        {
          id: 32346,
          province: "上海",
          children: [],
        },
        {
          id: 4234,
          province: "福建",
          children: ["福州", "厦门", "泉州", "莆田", "南平", "龙岩", "宁德"],
        },
        {
          id: 52346,
          province: "甘肃",
          children: ["兰州", "天水", "白银", "定西", "陇西", "武威"],
        },
        {
          id: 6324,
          province: "贵州",
          children: ["贵阳", "六盘水", "遵义", "安顺", "黔南", "毕节", "铜仁"],
        },
      ],
      // map过后的所有城市的数组
      NewAllCities: [],
      // 所有城市中子城市是否展开的变量
      childrenShow: true,
      // 热门城市的全选按钮
      HotAllActive: false,
      // 热门城市是否展开的变量
      hotShow: true,
      // 所有城市中省份的全选按钮
      allActive: false,
      // 用来存放用户选中的数据（本地存储（会话））
      checkCities: [],
      // 在checkCities数组不为0的时候 => 出现小箭头（点击之后） => 蒙版盒子出现的变量
      watch: false,
    };
  },
  methods: {
    handleActive(index) {
      this.newHotCities[index].flag = !this.newHotCities[index].flag;
      if (this.newHotCities[index].flag) {
        // 如果当前点击的城市被选中，则将其加入到已选择的城市列表中
        this.checkCities.push(this.hotCities[index]);
      } else {
        // 如果当前点击的城市被取消选中，则将其从已选择的城市列表中移除
        const cityIndex = this.checkCities.indexOf(this.hotCities[index]);
        if (cityIndex > -1) {
          this.checkCities.splice(cityIndex, 1);
        }
      }
      // 判断是否所有热门城市都被选中
      const allHotCitiesSelected = this.newHotCities.every((city) => city.flag);
      this.HotAllActive = allHotCitiesSelected;
    },
    handleCheckboxChange(event) {
      // 当 全选的选框选中时，更新newHotCities数组中每一项中flag的值 => 更新所有 span 的样式状态
      // => 并将newHotCities展开push进存到本地的数组checkCities中
      if (event.target.checked) {
        this.newHotCities.forEach((item) => {
          item.flag = true;
        });
        this.checkCities.push(...this.hotCities);
        console.log(this.checkCities);
      }
      // 当全选的选框未被选中时，
      else {
        this.newHotCities.forEach((item) => {
          item.flag = false;
        });
        this.checkCities = this.checkCities.filter(
          (city) => !this.hotCities.includes(city)
        );
        console.log(this.checkCities);
      }
    },
    handleCheckCity(provinceIndex, cityIndex, event) {
      // 更新子城市的选中状态
      const selected = event.target.checked;
      this.NewAllCities[provinceIndex].children[cityIndex].selected = selected;
      // 如果选中了子城市，添加到 checkCities 数组
      if (selected) {
        this.checkCities.push(
          this.NewAllCities[provinceIndex].children[cityIndex].name
        );
        this.checkCities = this.uniqueArray(this.checkCities);
        console.log(this.checkCities);
      } else {
        // 如果取消选中子城市，从 checkCities 数组移除
        const cityIndexInChecked = this.checkCities.indexOf(
          this.NewAllCities[provinceIndex].children[cityIndex].name
        );
        if (cityIndexInChecked > -1) {
          this.checkCities.splice(cityIndexInChecked, 1);
        }
        console.log(this.checkCities);
      }
      // 检查这个省份下的所有子城市是否都被选中了
      const allCitiesSelected = this.NewAllCities[provinceIndex].children.every(
        (city) => city.selected
      );
      // 根据子城市的选中状态更新省份的选中状态
      this.NewAllCities[provinceIndex].selected = allCitiesSelected;
      // 如果省份的选中状态发生变化，需要同步更新 checkbox 的显示状态
      // 这里使用 Vue.nextTick 确保 DOM 更新后再进行操作
      this.$nextTick(() => {
        const provinceCheckbox = this.$refs.checkbox[provinceIndex];
        if (provinceCheckbox) {
          provinceCheckbox.checked = allCitiesSelected;
        }
      });
    },
    clearChecked() {
      // 清除热门城市的选中状态
      this.newHotCities.forEach((city) => {
        city.flag = false;
      });
      // 清除所有城市的选中状态
      this.NewAllCities.forEach((province) => {
        province.selected = false; // 取消省份的选中状态
        province.children.forEach((city) => {
          city.selected = false; // 取消城市的选中状态
        });
      });
      // 清除选中城市列表
      this.checkCities = [];
      // 如果有全选按钮，也需要重置
      this.HotAllActive = false;
      // 重置观察状态
      this.watch = false;
    },
    confirmSelection() {
      sessionStorage.setItem("checkCities", JSON.stringify(this.checkCities));
    },
    cancelChecked(index) {
      // 获取要取消选中的城市名称
      const cityName = this.checkCities[index];
      // 从已选择的城市列表中移除
      this.checkCities.splice(index, 1);
      // 取消热门城市中对应的选中状态
      this.newHotCities = this.newHotCities.map((city) => {
        if (city.name === cityName) {
          return { ...city, flag: false };
        }
        return city;
      });
      // 取消所有城市中对应的选中状态
      this.NewAllCities = this.NewAllCities.map((province) => {
        const children = province.children.map((child) => {
          if (child.name === cityName) {
            return { ...child, selected: false };
          }
          return child;
        });
        // 检查该省份下是否还有选中的城市
        const isAnyCitySelected = children.some((child) => child.selected);
        return {
          ...province,
          selected: isAnyCitySelected, // 如果没有选中的城市，则省份也不选中
          children: children,
        };
      });
      // 更新全选状态
      this.HotAllActive = this.newHotCities.every((city) => city.flag);
    },
    handleProvinceChange(provinceIndex, event) {
      if (this.NewAllCities[provinceIndex].children.length > 0) {
        if (event.target.checked) {
          console.log(this.NewAllCities[provinceIndex].children);
          this.NewAllCities[provinceIndex].children.forEach((item) => {
            item.selected = true;
            this.checkCities.push(item.name);
          });
          this.checkCities = this.uniqueArray(this.checkCities);

          console.log(this.checkCities);
        } else {
          this.NewAllCities[provinceIndex].children.forEach((item) => {
            item.selected = false;
            const index = this.checkCities.indexOf(item.name);
            if (index > -1) {
              this.checkCities.splice(index, 1);
            }
          });

          console.log(this.checkCities);
        }
      } else {
        if (event.target.checked) {
          this.checkCities.push(this.NewAllCities[provinceIndex].province);
          console.log(this.checkCities);
        } else {
          const index = this.checkCities.indexOf(
            this.NewAllCities[provinceIndex].province
          );
          if (index > -1) {
            this.checkCities.splice(index, 1);
          }
          console.log(this.checkCities);
        }
      }
    },
    // 去重函数
    uniqueArray(arr) {
      return arr.filter((item, index, self) => {
        return self.indexOf(item) === index;
      });
    },
  },
  mounted() {
    this.newHotCities = this.hotCities.map((item) => {
      return { name: item, flag: false };
    });
    console.log(this.newHotCities[0]);
    // 对所有的城市数组allCities进行map，map之后的数据变成
    // {
    //   id: 15436,
    //   province: "安徽",
    //   flag:false
    //   children:[
    //     {flag:false,name:'合肥'}
    //   ]
    //  ["合肥", "芜湖", "安庆", "宿州", "淮南", "淮北", "宣城"],
    // }
    this.NewAllCities = this.allCities.map((item) => {
      let res = {
        ...item,
        flag: false,
        selected: false,
        children: item.children.map((ite) => ({
          flag: false,
          selected: false,
          name: ite,
        })),
      };
      return res;
    });
    console.log(this.NewAllCities[0]);
  },
  computed: {},
  
};
</script>

<style lang="less" scoped>
@import url("//at.alicdn.com/t/c/font_4355212_y69ouk21ecc.css");
.city_container {
  height: 100%;
}
.search {
  margin: 10px;
  height: 40px;
  background-color: white;
  display: flex;
  justify-content: center;
  input {
    width: 280px;
    height: 40px;
    border: 2px solid black;
    background-color: transparent;
    border-radius: 10px 0px 0px 10px;
    padding: 6px;
    box-sizing: border-box;
    font-size: 16px;
    border-right: 0px;
    outline: none;
    text-indent: 1em;
  }
  input::placeholder {
    color: gray;
    font-size: 13px;
  }
  span {
    display: flex;
    width: 60px;
    cursor: pointer;
    height: 40px;
    justify-content: center;
    align-items: center;
    background-color: transparent;
    border-radius: 0px 10px 10px 0px;
    border: 2px solid black;
    border-left: 0px;
  }
}
.content {
  height: 512px;
  overflow: auto;
}
.content::-webkit-scrollbar {
  display: none;
}
.hot_city {
  background-color: white;
  display: flex;
  .tag {
    width: 10px;
    height: 30px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    background-color: red;
  }
  .msg {
    width: 355px;
    overflow: auto;
  }
  .msg div:nth-child(1) {
    width: 355px;
    height: 30px;
    line-height: 30px;
    font-weight: 700;
    font-size: 17px;
    letter-spacing: 2px;
    padding: 0 10px;
    background-color: white;
  }
  .msg div:nth-child(2) {
    width: 355px;
    height: 40px;
    line-height: 40px;
    display: flex;
  }
  .msg div:nth-child(2) span:nth-child(1) {
    background-color: white;
    margin: 0 10px;
    cursor: pointer;
    i {
      font-size: 12px;
    }
  }
  .msg div:nth-child(2) span:nth-child(2) {
    background-color: white;
    letter-spacing: 1px;
    font-weight: 700;
    font-size: 14px;
  }
  .msg div:nth-child(2) span:nth-child(3) {
    background-color: white;
    letter-spacing: 1px;
    font-size: 12px;
    color: gray;
    margin-left: 10px;
    display: block;
    width: 140px;
    height: 40px;
    line-height: 40px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .msg div:nth-child(2) span:nth-child(4) {
    background-color: white;
    width: 20px;
    height: 40px;
    line-height: 40px;
    margin-left: 29px;
    text-align: center;
    label {
      height: 1.25rem;
      line-height: 1.25rem;
      display: inline-block;
      cursor: pointer;
      color: #333;
      margin-left: -20px;
    }
    input[type="checkbox"] {
      position: relative;
      width: 13px;
      height: 13px;
      line-height: 13px;
    }
    input[type="checkbox"]::before {
      content: "";
      position: absolute;
      top: -1px;
      left: -0.8px;
      width: 15px;
      height: 15px;
      line-height: 15px;
      text-align: center;
      color: white;
      font-size: 14px;
      background-color: white;
      border: 2px solid gainsboro;
      border-radius: 4px;
    }
    input[type="checkbox"]:checked::before {
      color: white;
      background-color: rgb(0, 119, 255);
      content: "✔";
    }
  }
  .msg div:nth-child(3) {
    width: 355px;
    height: 210px;
    overflow: visible;
    span {
      background-color: rgb(248, 248, 248);
      display: inline-block;
      border: 2px solid transparent;
      width: 70px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      letter-spacing: 2px;
      font-size: 14px;
      font-weight: 700;
      border-radius: 5px;
      margin-left: 13px;
      margin-right: 5px;
      margin-top: 10px;
    }
    .active {
      border-color: rgb(0, 119, 255);
      color: rgb(0, 119, 255);
    }
  }
  .msg div:nth-child(4) {
    width: 380px;
    height: 10px;
    background-color: rgb(248, 248, 248);
    margin-left: -10px;
  }
}
.all_city {
  height: 210px;
  display: flex;
  .tag {
    width: 10px;
    height: 30px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    background-color: rgb(0, 119, 255);
  }
  .msg {
    width: 355px;
    height: 220px;
  }
  .title {
    width: 355px;
    height: 30px;
    line-height: 30px;
    font-weight: 700;
    font-size: 17px;
    letter-spacing: 2px;
    padding: 0 10px;
    background-color: white;
  }
  .item {
    // display: flex;
    // flex-direction: column;
    width: 355px;
    // background-color: yellowgreen;
  }
  .father {
    width: 355px;
    border-bottom: 1px solid gainsboro;
    .jiantou {
      text-align: center;
      display: inline-block;
      width: 30px;
      height: 30px;
      line-height: 30px;
      i {
        font-size: 12px;
      }
    }
    .province {
      display: inline-block;
      width: 60px;
      height: 40px;
      line-height: 40px;
      letter-spacing: 2px;
      font-weight: 700;
      font-size: 14px;
      text-align: center;
    }
    .check {
      width: 30px;
      height: 30px;
      line-height: 30px;
      margin-left: 230px;
      text-align: right;
      label {
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        display: inline-block;
        cursor: pointer;
        color: #333;
      }
      input[type="checkbox"] {
        position: relative;
        width: 10px;
        height: 10px;
        line-height: 10px;
      }
      input[type="checkbox"]::before {
        content: "";
        position: absolute;
        top: -5px;
        left: -4px;
        width: 15px;
        height: 15px;
        line-height: 15px;
        text-align: center;
        color: white;
        font-size: 14px;
        background-color: white;
        border: 2px solid gainsboro;
        border-radius: 3px;
      }
      input[type="checkbox"]:checked::before {
        color: white;
        background-color: rgb(0, 119, 255);
        content: "✔";
      }
    }
  }
  .child {
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
    width: 330px;
    height: 40px;
    margin-left: 40px;
    // background-color: pink;
    // border-bottom: 1px solid gainsboro;
    .check {
      width: 30px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      margin-right: 25px;
      label {
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        display: inline-block;
        cursor: pointer;
        color: #333;
        // background-color: red;
      }
      input[type="checkbox"] {
        position: relative;
        width: 10px;
        height: 10px;
        line-height: 10px;
      }
      input[type="checkbox"]::before {
        content: "";
        position: absolute;
        top: -5px;
        left: -4px;
        width: 15px;
        height: 15px;
        line-height: 15px;
        text-align: center;
        color: white;
        font-size: 14px;
        background-color: white;
        border: 2px solid gainsboro;
        border-radius: 3px;
      }
      input[type="checkbox"]:checked::before {
        color: white;
        background-color: rgb(0, 119, 255);
        content: "✔";
      }
    }
    .children {
      width: 150px;
      line-height: 30px;
      height: 30px;
      font-size: 14px;
      font-weight: 700;
      letter-spacing: 2px;
      margin-right: 120px;
    }
  }
}
.rotate {
  transform: rotate(-180deg);
}
.rotated {
  transform: rotate(-90deg);
}
.antiRotated {
  transform: rotate(0deg);
}
.computed {
  width: 100vw;
  height: 55px;
  line-height: 55px;
  background-color: white;
  display: flex;
  position: fixed;
  z-index: 4;
  bottom: 0px;
  right: 0;
  font-size: 14px;
}
.computed div:nth-child(1) {
  width: 30%;
  text-align: center;
  .num {
    color: rgb(0, 119, 255);
  }
  .jiantou {
    i {
      font-size: 12px;
    }
  }
}
.computed div:nth-child(2),
.computed div:nth-child(3) {
  width: 35%;
  height: 55px;
  display: flex;
  align-items: center;
  justify-content: center;
  button {
    width: 100px;
    height: 35px;
    line-height: 35px;
    border: none;
    background-color: rgb(248, 248, 248);
    border-radius: 10px;
    color: gray;
    font-size: 13px;
    letter-spacing: 1px;
  }
}
.computed div:nth-child(3) {
  button {
    width: 80px;
    color: white;
    background-color: rgb(37, 82, 245);
  }
}
.watch {
  width: 100vw;
  height: 800px;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  position: fixed;
  z-index: 4;
  bottom: 0;
  right: 0;
  font-size: 14px;
  .example {
    width: 100vw;
    height: 300px;
    position: fixed;
    bottom: 0px;
    right: 0;
    display: flex;
    flex-direction: column;
    background-color: white;
    .title {
      width: 100vw;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid gainsboro;
    }
    .title span:nth-child(1) {
      display: block;
      width: 310px;
      height: 30px;
      line-height: 30px;
      text-align: left;
      letter-spacing: 1px;
      font-size: 16px;
      font-weight: 700;
    }
    .title span:nth-child(2) {
      display: block;
      width: 30px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      font-size: 18px;
      font-weight: 700;
      cursor: pointer;
      i {
        font-size: 18px;
      }
    }
    .city {
      width: 100vw;
      height: 230px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .city div:nth-child(1) {
      width: 91%;
      height: 30px;
      line-height: 30px;
      margin: 0 15px;
      font-size: 14px;
      font-weight: 700;
      letter-spacing: 1px;
      border-bottom: 1px solid gainsboro;
      span {
        color: rgb(0, 119, 255);
      }
    }
    .city div:nth-child(2) {
      width: 355px;
      height: 210px;
      overflow: auto;
      span {
        background-color: rgb(248, 248, 248);
        display: inline-block;
        box-sizing: border-box;
        width: 70px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        letter-spacing: 2px;
        font-size: 14px;
        font-weight: 700;
        border-radius: 5px;
        margin-left: 13px;
        margin-right: 5px;
        position: relative;
        margin-top: 10px;
        overflow: hidden;
        .mark {
          width: 30px;
          height: 30px;
          line-height: 24px;
          border-radius: 50%;
          background-color: rgb(243, 207, 206);
          color: red;
          position: absolute;
          text-align: left;
          padding-left: 2px;
          right: -27px;
          bottom: -10px;
        }
      }
    }
    .city div:nth-child(2)::-webkit-scrollbar {
      display: none;
    }
    .city::-webkit-scrollbar {
      display: none;
    }
  }
}
</style>